package com.android.namecard.model;


import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

import com.android.namecard.entity.Namecard;

public class NamecardDBHelper extends SQLiteOpenHelper {

	/**
	 * 插入名片函数
	 * @param name          名字
	 * @param career        职业
 	 * @param company       公司
 	 * @param address       地址
 	 * @param email         邮箱
	 * @param phone         电话
	 * @param qq            qq号码
	 * @param msn           msn号码
	 * @param website       网址
	 * @param business      业务
	 * @param type          名片类型
	 * @param front_image   名片正面图
	 * @param back_image    名片背面图
	 * @return
	 */
	public boolean insertNamecard(String name, String career, String company, String address, 
			String email, String phone, String qq, String msn, String website, String business, String type,
			Bitmap front_image, Bitmap back_image){
		byte[] front = this.getByteOfBitmap(front_image);
		byte[] back = this.getByteOfBitmap(back_image);
		SQLiteDatabase db = this.getWritableDatabase();
		//用系统时间作为id,这样不会出现重复
		String namecardId = String.valueOf(System.currentTimeMillis());
		//将信息先存入物件里
		ContentValues cv = new ContentValues();
		cv.put(NAMECARD_ID, namecardId);
		cv.put(NAME, name);
		cv.put(CAREER, career);
		cv.put(COMPANY, company);
		cv.put(ADDRESS, address);
		cv.put(EMAIL, email);
		cv.put(PHONE, phone);
		cv.put(QQ, qq);
		cv.put(MSN, msn);
		cv.put(WEBSITE, website);
		cv.put(BUSINESS, business);
		cv.put(TYPE, type);
		cv.put(FRONT_IMAGE, front);
		cv.put(BACK_IMAGE, back);
		
		try{
			db.insert(TABLE_NAME, null, cv);
			return true;
		}catch(SQLException e){
			Log.i("ERROR:",e.toString());
			return false;
		}finally{
			db.close();
		}
	}
	
	/**
	 * 
	 * @param info         接收到的字符串信息
	 * @param front_image  接收到的名片正面图
	 * @param back_image   接收到的名片背面图
	 * @return
	 */
	public boolean insertNamecardByReceive(String info, Bitmap front_image, Bitmap back_image){
		String[] infoString = info.split(Namecard.SPLIT);
		if(infoString.length==11){
			insertNamecard(infoString[0], infoString[1], infoString[2], infoString[3], infoString[4], infoString[5],
					infoString[6], infoString[7], infoString[8], infoString[9], infoString[10], front_image, back_image);
		}else{
			return false;
		}
		return true;
	}
	
	/**
	 * 获取所有名片的详细信息,这个为测试用方法
	 * @return
	 */
	public Namecard getNamecard(){
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cur = null;
		String[] col = {NAMECARD_ID, NAME, CAREER, COMPANY, ADDRESS, EMAIL, PHONE, QQ, MSN, WEBSITE, BUSINESS, TYPE, FRONT_IMAGE, BACK_IMAGE};
		try{
			cur = db.query(TABLE_NAME, col, null, null, null, null, null);
			if(!cur.isAfterLast()){
				cur.moveToFirst();
				Log.i("the cur position:", String.valueOf(cur.getPosition()));
				String namecardId = cur.getString(0);
				String name = cur.getString(1);
				String career = cur.getString(2);
				String company = cur.getString(3);
				String address = cur.getString(4);
				String email = cur.getString(5);
				String phone = cur.getString(6);
				String qq = cur.getString(7);
				String msn = cur.getString(8);
				String website = cur.getString(9);
				String business = cur.getString(10);
				String type = cur.getString(11);
				byte[] front = cur.getBlob(12);
				byte[] back = cur.getBlob(13);
				Bitmap front_image = this.getBitmapOfByte(front);
				Bitmap back_iamge = this.getBitmapOfByte(back);
				return new Namecard(namecardId, name, career, company, address, email, phone, qq, msn, website, business, type, front_image, back_iamge);
			}
			
		}catch(SQLException e){
			Log.i("ERROR:", e.toString());
			return null;
		}finally{
			db.close();
			if(cur!=null){
				cur.close();
			}
		}
		return null;
	}
	
	/**
	 * 根据类型获取名片列表
	 * @param type 类型有private,public,commercial,all 4种,分别对应私有名片,公用名片,商业名片,所有名片
	 * @return
	 */
	public ArrayList getNamecardListByType(String type){
		SQLiteDatabase db = this.getWritableDatabase();
		ArrayList namecardList = new ArrayList();
		Cursor cur = null;
		String[] col = {NAMECARD_ID, NAME, CAREER, COMPANY, TYPE};
		String whereClause = null;
		if(type==null || type.equals(NamecardDBHelper.ALL_TYPE)){
			whereClause = null;
		}else{
			whereClause = this.TYPE + " = '" + type + "'";
		}
		try{
			cur = db.query(TABLE_NAME, col, whereClause, null, null, null, null);
			if(cur!=null){
				cur.moveToFirst();
				while(!cur.isAfterLast()){
					String namecardId = cur.getString(0);
					String name = cur.getString(1);
					String career = cur.getString(2);
					String company = cur.getString(3);
					type = cur.getString(4);
					Namecard namecard = new Namecard(namecardId, name, career, company, null, null, null, null, null, null, null, type, null, null);
					namecardList.add(namecard);
					cur.moveToNext();
				}
			}
		}catch(SQLException e){
			Log.i("ERROR:", e.toString());
			return null;
		}finally{
			db.close();
			if(cur!=null){
				cur.close();
			}
		}
		return namecardList;
	}
	
	/**
	 * 获取某一id的名片详细信息
	 * @param namecardId  名片id
	 * @return 返回名片详细信息,不存在则返回null
	 */
	public Namecard getNamecardById(String namecardId){
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cur = null;
		String[] col = {NAMECARD_ID, NAME, CAREER, COMPANY, ADDRESS, EMAIL, PHONE, QQ, MSN, WEBSITE, BUSINESS, TYPE, FRONT_IMAGE, BACK_IMAGE};
		String whereClause = NAMECARD_ID + " = '" + namecardId + "'";
		try{
			cur = db.query(TABLE_NAME, col, whereClause, null, null, null, null);
			if(cur!=null){
				cur.moveToFirst();
				namecardId = cur.getString(0);
				String name = cur.getString(1);
				String career = cur.getString(2);
				String company = cur.getString(3);
				String address = cur.getString(4);
				String email = cur.getString(5);
				String phone = cur.getString(6);
				String qq = cur.getString(7);
				String msn = cur.getString(8);
				String website = cur.getString(9);
				String business = cur.getString(10);
				String type = cur.getString(11);
				byte[] front = cur.getBlob(12);
				byte[] back = cur.getBlob(13);
				Bitmap front_image = this.getBitmapOfByte(front);
				Bitmap back_iamge = this.getBitmapOfByte(back);
				return new Namecard(namecardId, name, career, company, address, email, phone, qq, msn, website, business, type, front_image, back_iamge);
			}
			
		}catch(SQLException e){
			Log.i("ERROR:",e.toString());
			return null;
		}finally{
			db.close();
			if(cur!=null){
				cur.close();
			}
		}
		return null;
	}
	
	/**
	 * 改变名片的分组
	 * @param namecardId 名片id
	 * @param type       改变后的分组
	 * @return
	 */
	public boolean updateNamecardTypeById(String namecardId, String type){
		SQLiteDatabase db = this.getWritableDatabase();
		
		//将信息先存入物件里
		ContentValues cv = new ContentValues();
		cv.put(TYPE, type);
		try{
			db.update(TABLE_NAME, cv, NAMECARD_ID + "=" + namecardId, null);
		}catch(Exception e){
			Log.i("ERROR:", e.toString());
			return false;
		}finally{
			db.close();
		}
		
		return true;
	}
	
	/**
	 * 删除某一id的名片记录
	 * @param namecardId 名片id
	 * @return
	 */
	public boolean deleteNamecardById(String namecardId){
		SQLiteDatabase db = this.getWritableDatabase();
		String whereClause = NAMECARD_ID + " = '" + namecardId + "'";
		try{
			db.delete(TABLE_NAME, whereClause, null);
			return true;
		}catch(SQLException e){
			Log.i("ERROR", e.toString());
			return false;
		}finally{
			db.close();
		}
	}
	
	/**
	 * 删除所有名片记录
	 * @return 
	 */
	public boolean deleteAllNamecards(){
		SQLiteDatabase db = this.getWritableDatabase();
		try{
			db.delete(TABLE_NAME, null, null);
			
			return true;
		}catch(SQLException e){
			Log.i("ERROR", e.toString());
			return false;
		}finally{
			db.close();
		}
		
	}
	
	/**
	 * 返回Bitmap对象的byte[]数组
	 * @param icon
	 * @return
	 */
	public static byte[] getByteOfBitmap(Bitmap icon){
		if (icon == null) {  
            return null;  
        }  
  
        // 最终图标要保存到浏览器的内部数据库中，系统程序均保存为SQLite格式，Browser也不例外，因为图片是二进制的所以使用字节数组存储数据库的  
        // BLOB类型  
        final ByteArrayOutputStream os = new ByteArrayOutputStream();  
        // 将Bitmap压缩成PNG编码，质量为100%存储          
        icon.compress(Bitmap.CompressFormat.PNG, 100, os);   
        // 构造SQLite的Content对象，这里也可以使用raw  
        return os.toByteArray();
	}
	
	/**
	 * 返回byte[]数组的Bitmap对象
	 * @param bit
	 * @return
	 */
	public static Bitmap getBitmapOfByte(byte[] b){
		Log.i("图片数组：",String.valueOf(b.length));
		if(b.length!=0){
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		}else {
		    return null;
		}
	}
	
	public NamecardDBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		String sql = "CREATE TABLE " + TABLE_NAME + " ( " 
		        + NAMECARD_ID + " text not null, "
		        + NAME + " text not null, " 
		        + CAREER + " text not null, " 
				+ COMPANY + " text not null, "
				+ ADDRESS + " text not null, "
				+ EMAIL + " , "
				+ PHONE + " text not null, "
				+ QQ + " , "
				+ MSN + " , "
				+ WEBSITE + " , "
				+ BUSINESS + " ,"
				+ TYPE + " , "
				+ FRONT_IMAGE + " , "
				+ BACK_IMAGE +
				" );";
			db.execSQL(sql);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	/***变量定义区***/
	public static final String PRIVATE_TYPE = "private";
	public static final String PUBLIC_TYPE = "public";
	public static final String COMMERCIAL_TYPE = "commercial";
	public static final String ALL_TYPE = "all";
	
	public static final String DATABASE_NAME = "dbNamecard.db";   //数据库名
	private static final int DATABASE_VERSION = 1;                 //数据库版本
	
	public static final String TABLE_NAME = "namecard";           //表名
	
	public static final String NAMECARD_ID = "namecard_id";       //名片id
	public static final String NAME = "name";                     //名字
	public static final String CAREER = "career";                 //职业
	public static final String COMPANY = "company";               //公司
	public static final String PHONE = "phone";                   //电话
	public static final String EMAIL = "email";                   //邮箱
	public static final String QQ = "qq";                         //qq号码
	public static final String MSN = "msn";                       //msn号码
	public static final String WEBSITE = "website";               //网址
	public static final String ADDRESS = "address";               //地址
	public static final String BUSINESS = "business";             //业务
	public static final String TYPE = "type";                     //名片类型
	public static final String FRONT_IMAGE = "front_image";       //名片正面图片
	public static final String BACK_IMAGE = "back_image";         //名片背面图片
	
}